package cn.yomigaeri.warn.service.impl;

import cn.yomigaeri.common.entity.po.Rule;
import cn.yomigaeri.warn.mapper.RuleMapper;
import cn.yomigaeri.warn.service.RuleService;
import com.github.benmanes.caffeine.cache.Cache;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.convert.ReadingConverter;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @ClassName: RuleServiceImpl
 * @Package: cn.yomigaeri.warn.service.impl
 * @Description:
 * @Author Yomigaeri
 * @Create 2025/6/5 11:18
 * @Version 1.0
 */
@Service
public class RuleServiceImpl implements RuleService {
    private final RuleMapper ruleMapper;
    private final Cache<String, List<Rule>> ruleCache;

    private static final String ALL_RULES_CACHE_KEY = "all_rules";

    @Autowired
    public RuleServiceImpl(RuleMapper ruleMapper, Cache<String, List<Rule>> ruleCache) {
        this.ruleMapper = ruleMapper;
        this.ruleCache = ruleCache;
    }

    /**
     * 获取所有rules并缓存
     */
    public List<Rule> getAllRulesWithCache() {
        return ruleCache.get(ALL_RULES_CACHE_KEY, key -> {
            // 当缓存不存在时，从数据库加载
            return ruleMapper.findAllRules();
        });
    }

    /**
     * 刷新缓存
     */
    public void refreshRuleCache() {
        // 先清除缓存
        ruleCache.invalidate(ALL_RULES_CACHE_KEY);
        // 然后重新加载
        getAllRulesWithCache();
    }

    /**
     * 直接获取缓存中的rules（不触发加载）
     */
    public List<Rule> getCachedRules() {
        return ruleCache.getIfPresent(ALL_RULES_CACHE_KEY);
    }
}
